<?php
/**
 * Created by PhpStorm.
 * User: Lin
 * Date: 2017/3/15 0015
 * Time: 下午 15:31
 */
Class CartAction extends CommonAction{

    //显示购物车视图
    public function index(){
        $cart=M('Cart');
        $userId=session('userId');
        $cartArr=$cart->where(array('user_id'=>$userId))->select();
        foreach ($cartArr as $k=>$v){
            $cartArr[$k]['goods']=M('goods')->where(array('id'=>$v['goods_id']))->find();
        }
        $this->cartArr=$cartArr;
        $this->display();
    }

    //AJAX请求 更新购物车或添加商品
    public function updateCart(){
        $data=array(
            'goods_id'=>I('goods_id','','intval'),
            'num'=>I('num','','intval'),
            'user_id'=>session('userId')
        );

        $db=M('cart');
        
        //从购物车删除商品
        if(empty($data['num'])){
            $where=array('user_id'=>$data['user_id'],'goods_id'=>$data['goods_id']);
            if($db->where($where)->delete()){
                exit(true);
            }else{
                exit(false);
            }
        }
        
        //更新购物车商品数量
        $update=I('update');
        $where=array('user_id'=>$data['user_id'],'goods_id'=>$data['goods_id']);
        if ($update){
            if($db->where($where)->save(array('num'=>$data['num']))){
                exit(true);
            }else{
                exit(false);
            }
        }else{//添加商品到购物车
            $goods=$db->where($where)->find();
            if($goods){//已存在该商品 更新数量
                if ($db->where($where)->save(array('num'=>$goods['num']+$data['num']))){
                    $userId=session('userId');
                    $cartCount=$db->where(array('user_id'=>$userId))->count();
                    exit($cartCount);
                }else{
                    exit(false);
                }
            }else{//添加商品进购物车
                if($db->add($data)){
                    $userId=session('userId');
                    $cartCount=$db->where(array('user_id'=>$userId))->count();
                    exit($cartCount);
                }else{
                    exit(false);
                }
            }
        }
    }
}